<template>
    <div class="edit">
        <van-nav-bar
            :title="pageTitle"
            left-arrow
            @click-left="$router.go(-1)"
            fixed
            placeholder
        />
        <van-form @submit="onSubmit">
            <van-field
                v-for="item in formItems"
                :key="item.model"
                v-model="prodInfo[item.model]"
                :name="item.name"
                :type="item.type"
                :label="item.label"
                :placeholder="item.placeholder"
                :rules="item.rules"
                autocomplete="off"
            />
            <van-field name="storeType" label="款式">
                <template #input>
                    <van-radio-group v-model="prodInfo.type" direction="horizontal">
                        <van-radio name="1">样衣</van-radio>
                        <van-radio name="2">商品</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                v-model="prodInfo.storeName"
                type="input"
                label="商家名称"
                name="商家名称"
                placeholder="请选择商家名称"
                @click="storeFocus"
                autocomplete="off"
                readonly
            />
            <van-field name="storeType" label="库存类型">
                <template #input>
                    <van-radio-group v-model="prodInfo.creaseType" direction="horizontal">
                        <van-radio name="1">出库</van-radio>
                        <van-radio name="2">入库</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                type="number"
                label="单价"
                name="单价"
            >
                <template #input>
                    <van-stepper v-model="prodInfo.price" min="0" decimal-length="2" />（元）
                </template>
            </van-field>
            <van-field
                type="number"
                label="数量"
                name="数量"
                
            >
                <template #input>
                    <van-stepper v-model="prodInfo.amount" />
                </template>
            </van-field>
            <van-field
                type="number"
                label="总价格"
                name="总价格"
                readonly
            >
                <template #input>
                    <span style="color: red;">￥{{ totalPrice }}</span>
                </template>
            </van-field>
            <van-field name="uploader" label="图片">
                <template #input>
                    <van-uploader
                        v-model="imgList"
                        accept="image/*"
                        max-count="1"
                        :after-read="uploadImg"
                        :capture="false"
                    />
                </template>
            </van-field>
            <van-field
                v-model="prodInfo.remark"
                type="textarea"
                label="描述"
                name="描述"
                maxlength="60"
                autosize
                show-word-limit
                autocomplete="off"
            />
            <van-field
                v-model="prodInfo.sendTime"
                type="input"
                label="创建时间"
                name="创建时间"
                @click="showPopup = true"
                autocomplete="off"
                readonly
            />
            <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit">提交</van-button>
            </div>
        </van-form>
    
        <van-popup v-model="showPopup" position="bottom">
            <van-datetime-picker v-model="sendTime" type="datetime" @cancel="showPopup = false" @confirm="onConfirm"/>
        </van-popup>
        <van-popup v-model="showStorePopup" position="bottom">
            <van-picker :loading="loadingStores" :columns="showStoreList" @confirm="onStoreConfirm" show-toolbar/>
        </van-popup>
    </div>
</template>

<script>
    import $axios from '@/assets/js/$axios.js';
    import compressorImage from '@/assets/js/compressorImage.js';
    import convertImage from '@/assets/js/convertImage.js';
    
    export default {
        data() {
            return {
                pageTitle: '',
                storeType: '',
                imgList: [],
                showPopup: false,
                showStorePopup: false,
                loadingStores: false,
                showStoreType: false,
                sendTime: new Date(),
                capture: 'camera',
                // storeName: '',
                storeList: [],
                prodInfo: {
                    code: '',
                    name: '',
                    type: '',
                    store: '',
                    storeName: '',
                    price: 0,
                    amount: 0,
                    photoUrl: '',
                    remark: '',
                    sendTime: '',
                    creaseType: ''
                },
                formItems: [
                    {
                        model: 'code',
                        name: '编号',
                        type: 'text',
                        label: '编号',
                        placeholder: '请输入编号',
                        rules: [{ required: true, message: '请输入编号' }]
                    },
                    {
                        model: 'name',
                        name: '商品名',
                        type: 'text',
                        label: '商品名',
                        placeholder: '请输入商品名',
                        rules: [{ required: true, message: '请输入商品名' }]
                    }
                ]
            }
        },
        computed: {
            totalPrice: function () {
                return this.prodInfo.amount * this.prodInfo.price;
            },
            showStoreList: function () {
                return this.storeList.map(item => {
                    return item.name;
                });
            }
        },
        created() {
            let route = this.$route;
            if (route.path.includes('add')) {
                this.pageTitle = '新增库存信息'
            } else if (route.path.includes('edit')) { // 暂时不用编辑功能
                this.pageTitle = '修改库存信息';
                this.prodInfo = this.$route.params;
            }
        },
        methods: {
            onStoreConfirm(store_name) {
                let obj = this.storeList.find(item => item.name = store_name);
                this.showStorePopup = false;
                
                this.prodInfo.store = obj.code;
                this.prodInfo.storeName = obj.name;
            },
            storeFocus() {
                this.showStorePopup = true;
                this.getStoreList();
            },
            getStoreList() {
                this.loadingStores = true;
                $axios.post2('/complain_test/api/getDictionaries', { types: 'store' }).then(res => {
                    this.loadingStores = false;
                    if (res.code === 200) {
                        this.storeList.splice(0);
                        this.storeList.push(...res.data.store);
                    }
                })
            },
            onConfirm(date) {
                this.showPopup = false;
                this.prodInfo.sendTime = new Date(date).format('yyyy-MM-dd hh:mm:ss');
            },
            onSubmit() {
                let prodInfo = this.prodInfo;
                
                if (!prodInfo.type) return this.$toast('请选择商品款式');
                if (!prodInfo.store) return this.$toast('请选择商家名称');
                if (!prodInfo.storeName) return this.$toast('请选择商家名称');
                if (!prodInfo.creaseType) return this.$toast('请选择库存类型');
                // if (!prodInfo.price) return this.$toast('请填写商品价格');
                // if (!prodInfo.amount) return this.$toast('请填写商品数量');
                if (!prodInfo.photoUrl) return this.$toast('请选择上传商品图片');
                if (!prodInfo.sendTime) return this.$toast('请填写创建时间');
                
                $axios.post('/complain_test/api/goods/save', {
                    ...this.prodInfo
                    // "amount": prodInfo.amount || 0,
                    // "code": prodInfo.code || '',
                    // "name": prodInfo.name || '',
                    // "price": prodInfo.price || '',
                    // "remark": prodInfo.remark || '',
                    // "photoUrl": prodInfo.photoUrl || '',
                    // "type": prodInfo.type, // 款式要下拉选择
                    // 'store': prodInfo.store,
                    // "storeName": prodInfo.storeName || '',
                    // "sendTime": prodInfo.sendTime,
                    // "creaseType": prodInfo.creaseType
                }).then(res => {
                    // console.log('新增', res);
                    if (res.code === 200) {
                        this.$toast(res.msg);
                        this.$router.replace({ name: 'home' })
                    } else {
                        this.$toast(res.msg || '提交失败');
                    }
                })
            },
            async uploadImg() {
                let formData = new FormData();
                let img = this.imgList[0].file;
                
                // formData.append('file', this.imgList[0].file);
                console.log('压缩前', img);
    
                // const fileType = img.name.substring(img.name.indexOf('.') + 1);
    
                // 判断文件是不是jpeg 不是jpeg的都转成jpeg
                // if (!['jpeg', 'jpg'].includes(fileType)) {
                //     img = await convertImage(img);  //转陈jpeg格式的file
                // }
    
                if (img.size > 3 * 1024 * 1024) {
                    img = await compressorImage(img, 'file', 3 * 1024 * 1024 / img.size); //图片压缩
                }
                
                console.log('压缩后', img);
                formData.append('file', img);
                
                $axios.postImg('/complain_test/api/upload/fileUpload', formData)
                    .then(res => {
                        // console.log('uploadImg', res);
                        if (res.code === 0) this.prodInfo.photoUrl = res.url;
                        else {
                            this.imgList.splice(0);
                            this.$toast('上传失败')
                        }
                        
                    })
            },
        },
        watch: {
        
        }
    }
</script>

<style lang="less" scoped>
    /deep/ .van-stepper__input {
        width: 1.8rem;
        font-size: .32rem;
    }
    .edit {
        width: 100vw;
    }
</style>
